import React, { memo, useEffect, useRef, useState } from 'react';
import {
  ConfigProvider,
  Divider,
  Table,
  Modal,
  Button,
  Form,
  Input,
  Popconfirm,
  Space,
  Dropdown,
  message,
  Drawer,
  Menu,
  Descriptions,
  Col,
  Row,
  Select
} from 'antd';
import { ProForm } from '@/base-ui';
import DivWrapper from './style';
import zhCN from 'antd/es/locale/zh_CN';
import TipsHeader from '@/components/TipsHeader';
import chickenHousePicture from '@/assets/img/chicken-house.png';
import http from '@/services/request';
import {
  PageSearchConfig,
  SearchSelector,
  DataType,
  UseSearch
} from './config';
//form
const NewForm = (props: any) => {
  const { houseList, houseMap } = props;
  const changeId = (value, option) => {
    props.newref.current.setFieldValue('chickenHouseName', option.label);
    props.newref.current.setFieldValue('houseResponsiblePhone', houseMap.get(value).responsiblePhone);
    props.newref.current.setFieldValue('houseResponsibleName', houseMap.get(value).responsibleName);
  };

  return (
    <Form ref={props.newref} layout={'vertical'} style={{ minHeight: '100%', flex: 1, overflow: 'auto', width: '100%', overflowX: 'hidden' }}>
      <Row >
        <Col xs={{ span: 5, offset: 4 }} lg={{ span: 6, offset: 3 }}>
          <Form.Item
            label="请选择鸡舍"
            name="chickenHouseId"
            rules={[{ required: true, message: '请选择鸡舍' }]}
          >
            <Select style={{ width: 120 }} options={houseList} onChange={changeId} />
          </Form.Item>
          <Form.Item
            name="chickenHouseName"
            label="当前鸡舍名称"
          >
            <Input disabled />
          </Form.Item>
          <Form.Item
            label="当前鸡舍负责人电话"
            name="houseResponsiblePhone"
          >
            <Input disabled />
          </Form.Item>
          <Form.Item
            label="当前鸡舍负责人名称"
            name="houseResponsibleName"
          >
            <Input disabled />
          </Form.Item>
        </Col>
        <Col xs={{ span: 5, offset: 4 }} lg={{ span: 6, offset: 3 }}>
          <Form.Item
            label="请输入批次品种"
            name="batchVariety"
            rules={[{ required: true, message: '请输入批次品种' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="remark"
            label="请备注"
            rules={[{ required: true, message: '请备注' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="inQuantity"
            label="请输入入舍数量"
            rules={[{ required: true, message: '请输入出栏数量' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="transferTime"
            label="请输入入舍时间"
            rules={[{ required: true, message: '请输入入舍时间' }]}
          >
            <Input />
          </Form.Item>
        </Col>
      </Row>
    </Form>
  );
};

//按钮组
const Buttongroup = (props: any) => {
  return (
    <div style={{ marginBottom: 10, float: 'left' }}>
      <Button
        type="primary"
        onClick={() => props.add()}
        style={{ marginRight: 10 }}
      >
        新增记录
      </Button>
      <Button
        danger
        onClick={() => {
          props.checkIt();
        }}
        style={{ marginRight: 10 }}
      >
        批量删除
      </Button>


    </div>
  );
};

const BuyBack = memo(() => {
  //复选框的内容设定
  const [selectionType] = useState<'checkbox' | 'radio'>('checkbox');
  const [houseList, setHouseList] = useState([]);
  const [houseMap, setHouseMap] = useState(new Map());
  //更多功能定位id
  const [drawerID, setDrawerID]: any = useState({});
  //抽屉开关
  const [DrawerVisible, setDrawerVisible] = useState(false);
  //复选框批量删除
  const [itemSelected, setItemSelected] = useState<React.Key[]>([]);

  //是否新增
  const [edited, setEdited]: any = useState('');
  //高级检索
  const [isMoreSearchShow, setisMoreSearchShow]: any = useState(false);
  const newref: any = useRef();
  const [dataSource, setdataSource]: any = useState([]);
  const [searchMore, setSearchMore] = useState(false);
  // 控制对话框显示（新增）
  const [addModalVisible, setAddModalVisible] = useState(false);
  useEffect(() => {
    http.get('/feed/chicken/chickenInHouseFarming/list/1/30').then((res) => {
      setdataSource(res.data.records);
    });
    http.get('/feed/chicken/chickenHouseFarming/findAll').then((res) => {
      const list = res.data?.map(item => {
        return { value: item.chickenHouseId, label: item.chickenHouseName };
      });
      const map = new Map();
      res.data?.forEach(item => {
        map.set(item.chickenHouseId, item);
      });
      setHouseMap(map);
      setHouseList(list);
    });
  }, []);

  const rowSelection = {
    onChange: (selectedRowKeys: React.Key[]) => {
      setItemSelected(selectedRowKeys);
    },
    getCheckboxProps: (record: DataType) => ({
      disabled: record.name === 'Disabled User', // Column configuration not to be checked
      name: record.name
    })
  };

  const checkIt = () => {
    http({
      url: `/feed/chicken/chickenInHouseFarming/deletion/batch`,
      method: 'delete',
      data: JSON.stringify(itemSelected),
      headers: { 'Content-Type': 'application/json' }
    }).then(() => {
      http.get('/feed/chicken/chickenInHouseFarming/list/1/30').then((res) => {
        setdataSource(res.data.records);
      });
    });
  };

  //导出
  const exported = () => {
    http({
      method: 'get',
      url: '/server/dailySlaughter/export',
      data: JSON.stringify([1, 4]),
      responseType: 'blob',
      headers: {
        'Content-Type': 'application/json'
      }
    }).then((res: any) => {
      const blob = new Blob([res.data], {
        // res 为后台返回数据
        type: 'application/vnd.ms-excel;charset=utf-8' // 导出数据生成excel的格式设置
      });
      if ('download' in document.createElement('a')) {
        // 非IE下载
        const elink = document.createElement('a');
        elink.download = Date.now() + `.xlsx`;
        elink.style.display = 'none';
        elink.target = '_blank';
        elink.href = window.URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
      }
    });
  };

  // 对话框确认
  const handleAddModalOk = () => {
    setAddModalVisible(false);
    // 修改操作
    if (edited) {
      const newedited = newref.current.getFieldsValue();
      http
        .put(`/feed/chicken/chickenInHouseFarming/update/${edited.id}`, {
          ...newedited
        })
        .then(() => {
          http
            .get('/feed/chicken/chickenInHouseFarming/list/1/30')
            .then((res) => {
              setdataSource(res.data.records);
            });
        });
      setEdited(null);
      return;
    }
    //id不在--就是新增
    const addData = newref.current.getFieldsValue();
    const {
      chickenHouseId,
      chickenHouseName,
      houseResponsibleName,
      batchVariety,
      inQuantity,
      transferTime,
      houseResponsibleId,
      houseResponsiblePhone,
      remark
    } = addData;

    http
      .post('/feed/chicken/chickenInHouseFarming/save', {
        chickenHouseId,
        chickenHouseName,
        houseResponsibleName,
        batchVariety,
        inQuantity,
        transferTime,
        houseResponsibleId,
        houseResponsiblePhone,
        remark
      })
      .then(() => {
        http
          .get('/feed/chicken/chickenInHouseFarming/list/1/30')
          .then((res) => {
            setdataSource(res.data.records);
          });
      })
      .catch((error) => {
        // eslint-disable-next-line no-console
        console.log(error);
      });
  };

  //编辑
  const edit = (id: any) => {
    setAddModalVisible(true);
    setTimeout(() => {
      newref.current.setFieldsValue({
        ...id
      });
      setEdited(id);
    }, 0);
  };

  // 对话框取消
  const handleAddModalCancel = () => {
    setAddModalVisible(false);
  };
  const add = () => {
    setTimeout(() => {
      newref.current.setFieldsValue({
        repoId: '',
        batchNumber: '',
        productName: '',
        matName: '',
        supplier: '',
        money: '',
        cases: '',
        quantity: '',
        weight: '',
        unit: ''
      });
    });
    setAddModalVisible(true);
  };

  const indexTable = {
    pagination: {
      //每页 10 条项目
      defaultPageSize: 10,
      //自定义每页显示数目
      showSizeChanger: true,
      //当前的页数和大小
      onShowSizeChange: (current: any, pageSize: any) => { },
      //自定义每页显示项目的选项
      pageSizeOptions: ['5', '10', '15'],

      // 输入指定页码跳页
      showQuickJumper: true,
      //跳页之后的回调函数
      onShowQuickJump: (page: any) => { },
      //全部项目数（最好可以用变量表示，与实际项目数关联）
      total: dataSource?.length,
      // 改变的回调函数
      onChange: (page: any) => { }
    }
  };

  const FormColumns: any = [
    {
      title: '鸡舍编号',
      dataIndex: 'chickenHouseId',
      key: 'chickenHouseId',
      width: 100
    },
    {
      title: '鸡舍名称',
      dataIndex: 'chickenHouseName',
      key: 'chickenHouseName',
      width: 100
    },
    {
      title: '鸡舍方负责人名称',
      dataIndex: 'houseResponsibleName',
      key: 'houseResponsibleName',
      width: 100
    },
    {
      title: '肉鸡品种',
      dataIndex: 'batchVariety',
      key: 'batchVariety',
      width: 100
    },
    {
      title: '入舍数量(只)',
      dataIndex: 'inQuantity',
      key: 'inQuantity',
      width: 100
    },
    {
      title: '入舍时间',
      dataIndex: 'transferTime',
      key: 'transferTime',
      width: 100
    },
    {
      title: '鸡舍方负责人联系电话',
      dataIndex: 'houseResponsiblePhone',
      key: 'houseResponsiblePhone',
      width: 100
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
      width: 150
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      width: 150,
      render: (_: any, record: any) => (
        <Space>
          <a onClick={() => edit(record)}>编辑</a>
          <Popconfirm
            title="确定删除?"
            okText="确认"
            cancelText="取消"
            onConfirm={() => {
              http
                .delete(
                  `/feed/chicken/chickenInHouseFarming/delete/${record.id}`
                )
                .then(() => {
                  const newData = dataSource.filter(
                    (item: { id: any }) => item.id !== record.id
                  );
                  setdataSource(newData);
                });
            }}
          >
            <a style={{ color: '#ff4d4f' }}>删除</a>
          </Popconfirm>
          <Dropdown overlay={menu(record)}>
            <a
              onClick={(e) => {
                e.preventDefault();
              }}
            >
              ···
            </a>
          </Dropdown>
        </Space>
      ),
      fixed: 'right'
    }
  ];

  const menu = (item: any) => (
    <Menu
      items={[
        {
          key: 0,
          label: (
            <Button
              type="primary"
              onClick={() => {
                showDrawer(item);
              }}
            >
              详情
            </Button>
          )
        },
        {
          key: 2,
          label: (
            <Button
              onClick={function () {
                window.print();
              }}
            >
              打印
            </Button>
          )
        }
      ]}
    />
  );

  // 高级检索 条件查询 /server/feeVoucherSlaughter/get

  const onFinish = (form: any) => {
    // form.inQuantity = parseInt(form.inQuantity)
    // 发送请求
    http
      .post('/feed/chicken/chickenInHouseFarming/get', form)
      .then((res: any) => {
        if (res.statusCode !== 20000) {
          return message.error('查询失败');
        }
        const data = res.data || [];
        setdataSource(data);
      });
  };
  //详情--抽屉
  const showDrawer = (data: any) => {
    setDrawerVisible(true);
    http
      .get(`/feed/chicken/chickenInHouseFarming/get/${data.id}`)
      .then((res) => {
        setDrawerID(res.data);
      });
  };

  const onDraweClose = () => {
    setDrawerVisible(false);
  };

  const renderDescription = () => (
    <>
      <p>肉鸡入舍管理可以帮助您更加方便地管理和记录肉鸡的入舍情况。</p>
      <p>通过使用肉鸡入舍管理，您可以更加方便地管理和记录肉鸡的入舍情况，避免了手动记录的繁琐和错误，提高了管理效率。</p>
    </>
  )

  return (
    <DivWrapper>
      <TipsHeader imgSrc={chickenHousePicture} title="肉鸡入舍" description={renderDescription()} />
      {searchMore && (
        <div>
          <ProForm formItems={PageSearchConfig} onFinish={onFinish} />
          <Divider style={{ margin: '10px 0 20px' }} />
        </div>
      )}
      <Buttongroup
        checkIt={() => checkIt()}
        add={() => add()}
        exported={() => exported()}
      />
      <UseSearch
        setisMoreSearchShow={(e: any) => {
          setisMoreSearchShow(e);
        }}
        isMoreSearchShow={isMoreSearchShow}
        setsearchMore={(e: boolean) => setSearchMore(e)}
      />
      <SearchSelector
        dataSource={(e: any) => setdataSource(e)}
      ></SearchSelector>
      <ConfigProvider locale={zhCN}>
        <Table
          dataSource={dataSource}
          columns={FormColumns}
          scroll={{ x: 1300 }}
          pagination={indexTable.pagination}
          rowKey={(i) => i.id}
          rowSelection={{
            type: selectionType,
            ...rowSelection
          }}
        />
      </ConfigProvider>
      <Drawer
        title="详情"
        placement="right"
        size="large"
        onClose={onDraweClose}
        visible={DrawerVisible}
      >
        <Descriptions
          title={`编号：${drawerID.id}`}
          bordered
          style={{ width: '450px' }}
        >
          <Descriptions.Item label="鸡舍名">
            {drawerID.chickenHouseName}
          </Descriptions.Item>
          <Descriptions.Item label="鸡舍编号">
            {drawerID.chickenHouseId}
          </Descriptions.Item>
          <Descriptions.Item label="鸡舍负责人编号">
            {drawerID.houseResponsibleId}
          </Descriptions.Item>
          <Descriptions.Item label="鸡舍负责人电话">
            {drawerID.houseResponsiblePhone}
          </Descriptions.Item>
          <Descriptions.Item label="鸡舍负责人名称">
            {drawerID.houseResponsibleName}
          </Descriptions.Item>
          <Descriptions.Item label="批次品种">
            {drawerID.batchVariety}
          </Descriptions.Item>
          <Descriptions.Item label="入舍数量">
            {drawerID.inQuantity}
          </Descriptions.Item>
          <Descriptions.Item label="入舍时间">
            {drawerID.transferTime}
          </Descriptions.Item>
          <Descriptions.Item label="备注">{drawerID.remark}</Descriptions.Item>
        </Descriptions>
      </Drawer>
      <Modal
        width={'800px'}
        bodyStyle={{
          height: '400px',
          display: 'flex',
          flexDirection: 'column-reverse',
        }}
        title="新增记录"
        visible={addModalVisible}
        onOk={handleAddModalOk}
        onCancel={handleAddModalCancel}
      >
        <NewForm newref={newref} houseList={houseList} houseMap={houseMap} />
      </Modal>
    </DivWrapper>
  );
});
export default BuyBack;
